<?php
/**
 * @copyright	Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;
jimport('joomla.application.component.modeladmin');
class ExercisesModelResult extends JModelAdmin
{
	protected function canDelete($record)
	{
		if (!empty($record->id)) {
				if ($record->state != -2) {
					return ;
				}
			$user = JFactory::getUser();

			return $user->authorise('core.delete', 'com_exercises.component');
		}
	}
	protected function canEditState($record)
	{
		$user = JFactory::getUser();
                return $user->authorise('core.edit.state', 'com_exercises.component');
		
	}
	public function getTable($type = 'Result', $prefix = 'ExercisesTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_exercises.result', 'result', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_exercises.edit.result.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		}

		return $data;
	}
	protected function prepareTable($table)
	{
		$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);
	}
        public function getItem($pk = null) {
            $item = parent::getItem($pk);
            $item->resultdetail = $this->getResultDetail($item->id);
            return $item;
        }
        public function getResultDetail($id){
            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
            $query->select('eq.name,eq.question,ea.answer,ea.point')->from('#__exercises_results_questions_anwers AS erqa')
                    ->leftJoin('#__exercises_questions as eq ON erqa.questionid = eq.id')
                    ->leftJoin('#__exercises_answers as ea ON erqa.answersid = ea.id')
                    ->where('resultid = '.(int)$id);
            $db->setQuery($query);
            return $db->loadObjectList();
        }
}
